<template>
  <el-drawer
    title="器具详情"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="80%"
    custom-class="drawer-container"
    @open="handleOpen"
  >
    <div class="drawer-content">
      <el-tabs v-model="activeTabValue" type="card" @tab-click="handleTabClick">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="器具编码">{{ detailForm.containerCode }}</el-descriptions-item>
            <el-descriptions-item label="器具型号编码">{{ detailForm.materialCode }}</el-descriptions-item>
            <el-descriptions-item label="器具型号名称">{{ detailForm.materialName }}</el-descriptions-item>
            <el-descriptions-item label="生产日期">{{ parseTime(detailForm.productionDate, '{y}-{m}-{d}') }}</el-descriptions-item>
            <el-descriptions-item label="当前仓库">{{ detailForm.currentWarehouseName }}</el-descriptions-item>
            <el-descriptions-item label="位置状态">
              <el-tag v-if="detailForm.locationStatus == '1'" type="success" size="mini">在库</el-tag>
              <el-tag v-else-if="detailForm.locationStatus == '2'" type="warning" size="mini">在途</el-tag>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="业务状态">
              <el-tag v-if="detailForm.businessStatus == '1'" type="success" size="mini">正常</el-tag>
              <el-tag v-else-if="detailForm.businessStatus == '2'" type="info" size="mini">封存</el-tag>
              <el-tag v-else-if="detailForm.businessStatus == '3'" type="warning" size="mini">维修</el-tag>
              <el-tag v-else-if="detailForm.businessStatus == '4'" type="danger" size="mini">报废</el-tag>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="装箱状态">
              <el-tag v-if="detailForm.packingStatus == '1'" type="info" size="mini">空箱</el-tag>
              <el-tag v-else-if="detailForm.packingStatus == '2'" type="success" size="mini">满箱</el-tag>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="定位器编码">{{ detailForm.locatorCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="当前项目">{{ detailForm.currentProjectName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="当前物料编码">{{ detailForm.currentMaterialCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="当前物料名称">{{ detailForm.currentMaterialName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="当前物料数量">{{ detailForm.currentMaterialQuantity || '-' }}</el-descriptions-item>
            <el-descriptions-item label="最后装箱时间">{{ parseTime(detailForm.lastPackingTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}</el-descriptions-item>
            <el-descriptions-item label="最后拆箱时间">{{ parseTime(detailForm.lastUnpackingTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}</el-descriptions-item>
            <el-descriptions-item label="最后上报时间">{{ parseTime(detailForm.lastUploadTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}</el-descriptions-item>
            <el-descriptions-item label="最后位置">{{ detailForm.lastAddress || '-' }}</el-descriptions-item>
            <el-descriptions-item label="当前内衬方案" :span="2">{{ detailForm.currentLiningScheme || '-' }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ parseTime(detailForm.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <!-- 器具操作记录标签页 -->
        <el-tab-pane label="操作记录" name="operation">
          <div class="tab-content">
            <el-table
              v-loading="operationLoading"
              :data="operationList"
              border
              style="width: 100%"
              empty-text="暂无操作记录"
            >
              <el-table-column prop="operationTime" label="操作时间" width="180" align="center">
                <template slot-scope="scope">
                  {{ parseTime(scope.row.operationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                </template>
              </el-table-column>
              <el-table-column prop="operationType" label="操作类型" width="120" align="center">
                <template slot-scope="scope">
                  <el-tag :type="getOperationTypeTag(scope.row.operationType)" size="mini">
                    {{ getOperationTypeName(scope.row.operationType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createBy" label="操作人员" width="120" align="center" />
              <el-table-column label="操作仓库" width="200" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.warehouse ? scope.row.warehouse.warehouseName : '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="operationDetail" label="操作描述" min-width="200" show-overflow-tooltip />
              <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
            </el-table>
            <pagination
              v-show="operationTotal > 0"
              :total="operationTotal"
              :page.sync="operationQueryParams.pageNum"
              :limit.sync="operationQueryParams.pageSize"
              @pagination="handleOperationPagination"
            />
          </div>
        </el-tab-pane>

        <!-- 器具移库记录标签页 -->
        <el-tab-pane label="移库记录" name="transfer">
          <div class="tab-content">
            <el-table
              v-loading="transferLoading"
              :data="transferList"
              border
              style="width: 100%"
              empty-text="暂无移库记录"
            >
              <el-table-column prop="sourceWarehouseName" label="源库房" width="150" align="center" show-overflow-tooltip />
              <el-table-column prop="targetWarehouseName" label="目标库房" width="150" align="center" show-overflow-tooltip />
              <el-table-column prop="materialCode" label="物料编码" width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="materialName" label="物料名称" width="180" align="center" show-overflow-tooltip />
              <el-table-column prop="projectCode" label="项目编码" width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="projectName" label="项目名称" width="150" align="center" show-overflow-tooltip />
              <el-table-column prop="operatorName" label="操作人员" width="120" align="center" />
              <el-table-column prop="transferStatus" label="状态" width="100" align="center">
                <template slot-scope="scope">
                  <el-tag :type="getTransferStatusTag(scope.row.transferStatus)" size="mini">
                    {{ getTransferStatusName(scope.row.transferStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="出库时间" width="180" align="center">
                <template slot-scope="scope">
                  {{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                </template>
              </el-table-column>
              <el-table-column prop="updateTime" label="入库时间" width="180" align="center">
                <template slot-scope="scope">
                  {{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="transferTotal > 0"
              :total="transferTotal"
              :page.sync="transferQueryParams.pageNum"
              :limit.sync="transferQueryParams.pageSize"
              @pagination="handleTransferPagination"
            />
          </div>
        </el-tab-pane>

        <!-- 定位日志记录标签页 -->
        <el-tab-pane label="定位日志" name="location">
          <div class="tab-content">
            <el-table
              v-loading="locationLoading"
              :data="locationList"
              border
              style="width: 100%"
              empty-text="暂无定位记录"
            >
              <el-table-column prop="createTime" label="定位时间" width="180" align="center">
                <template slot-scope="scope">
                  {{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                </template>
              </el-table-column>
              <el-table-column prop="longitude" label="经度" width="120" align="center" />
              <el-table-column prop="latitude" label="纬度" width="120" align="center" />
              <el-table-column prop="uploadAddress" label="位置描述" min-width="200" show-overflow-tooltip />
              <el-table-column prop="temperature" label="温度" width="100" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.temperature !== null && scope.row.temperature !== undefined">{{ scope.row.temperature }}°C</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="humidity" label="湿度" width="100" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.humidity !== null && scope.row.humidity !== undefined">{{ scope.row.humidity }}%</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="shockLevel" label="震动等级" width="120" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-if="scope.row.shockLevel !== null && scope.row.shockLevel !== undefined">{{ scope.row.shockLevel }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="batteryLevel" label="电量" width="80" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.batteryLevel">{{ scope.row.batteryLevel }}%</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="locationTotal > 0"
              :total="locationTotal"
              :page.sync="locationQueryParams.pageNum"
              :limit.sync="locationQueryParams.pageSize"
              @pagination="handleLocationPagination"
            />
          </div>
        </el-tab-pane>

        <!-- 轨迹地图标签页 -->
        <el-tab-pane label="轨迹地图" name="track">
          <div class="tab-content">
            <div class="track-map-container">
              <!-- 地图容器 -->
              <div
                id="track-map"
                ref="trackMap"
                class="track-map"
                :class="{ 'fullscreen': isFullscreen }"
              ></div>

              <!-- 全屏/退出全屏按钮 -->
              <el-button
                class="fullscreen-btn"
                type="primary"
                size="mini"
                :icon="isFullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen'"
                @click="toggleFullscreen"
              >
                {{ isFullscreen ? '退出全屏' : '全屏' }}
              </el-button>

              <!-- 播放控制器 -->
              <div class="track-controls" v-if="trackPoints.length > 0">
                <div class="control-buttons">
                  <el-button
                    type="primary"
                    size="mini"
                    :icon="isPlaying ? 'el-icon-video-pause' : 'el-icon-video-play'"
                    @click="togglePlay"
                  >
                    {{ isPlaying ? '暂停' : '播放' }}
                  </el-button>

                  <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetTrack"
                  >
                    重置
                  </el-button>
                </div>

                <div class="speed-control">
                  <span>播放速度：</span>
                  <el-select v-model="playSpeed" size="mini" style="width: 80px;">
                    <el-option label="0.5x" :value="0.5"></el-option>
                    <el-option label="1x" :value="1"></el-option>
                    <el-option label="2x" :value="2"></el-option>
                    <el-option label="5x" :value="5"></el-option>
                  </el-select>
                </div>

                <div class="progress-control">
                  <span>进度：</span>
                  <el-slider
                    v-model="playProgress"
                    :max="trackPoints.length - 1"
                    :step="1"
                    :show-tooltip="false"
                    @change="onProgressChange"
                    style="width: 200px; margin: 0 10px;"
                  ></el-slider>
                  <span>{{ currentPointIndex + 1 }} / {{ trackPoints.length }}</span>
                </div>
              </div>

              <!-- 无数据提示 -->
              <div v-if="trackPoints.length === 0" class="no-data">
                <i class="el-icon-location-outline"></i>
                <p>暂无轨迹数据</p>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-drawer>
</template>

<script>
export default {
  name: 'ContainerDetailDrawer',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detailForm: {
      type: Object,
      default: () => ({})
    },
    activeTab: {
      type: String,
      default: 'basic'
    },
    operationList: {
      type: Array,
      default: () => []
    },
    operationTotal: {
      type: Number,
      default: 0
    },
    operationLoading: {
      type: Boolean,
      default: false
    },
    operationQueryParams: {
      type: Object,
      default: () => ({})
    },
    transferList: {
      type: Array,
      default: () => []
    },
    transferTotal: {
      type: Number,
      default: 0
    },
    transferLoading: {
      type: Boolean,
      default: false
    },
    transferQueryParams: {
      type: Object,
      default: () => ({})
    },
    locationList: {
      type: Array,
      default: () => []
    },
    locationTotal: {
      type: Number,
      default: 0
    },
    locationLoading: {
      type: Boolean,
      default: false
    },
    locationQueryParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 地图相关
      map: null,
      trackPoints: [],
      trackPolyline: null,
      currentMarker: null,
      isPlaying: false,
      isFullscreen: false,
      playSpeed: 1,
      playProgress: 0,
      currentPointIndex: 0,
      playTimer: null,
      markers: [],
      // 新增属性
      trackPointMarkers: [], // 轨迹点标记
      routePolylines: [], // 路径规划线段
      infoWindow: null, // 信息窗体
      driving: null // 路径规划服务
    }
  },
  computed: {
    drawerVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    activeTabValue: {
      get() {
        return this.activeTab
      },
      set(val) {
        this.$emit('update:activeTab', val)
      }
    },
    // 处理轨迹数据
    processedTrackData() {
      console.log('=== 轨迹数据处理调试 ===')
      console.log('原始locationList:', this.locationList)
      console.log('locationList长度:', this.locationList ? this.locationList.length : 0)

      if (!this.locationList || this.locationList.length === 0) {
        console.log('没有定位数据，返回空数组')
        return []
      }

      // 筛选最近30天的数据
      const thirtyDaysAgo = new Date()
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
      console.log('30天前的时间:', thirtyDaysAgo)

      const filteredData = this.locationList
        .filter(item => {
          const itemDate = new Date(item.createTime)
          const hasValidCoords = item.longitude && item.latitude
          const isWithinTimeRange = itemDate >= thirtyDaysAgo

          console.log(`数据项: ${item.createTime}, 坐标: ${item.longitude},${item.latitude}, 时间范围内: ${isWithinTimeRange}, 坐标有效: ${hasValidCoords}`)

          return isWithinTimeRange && hasValidCoords
        })
        .sort((a, b) => new Date(a.createTime) - new Date(b.createTime))
        .map(item => ({
          lng: parseFloat(item.longitude),
          lat: parseFloat(item.latitude),
          time: item.createTime,
          address: item.uploadAddress || '未知位置',
          temperature: item.temperature,
          humidity: item.humidity,
          batteryLevel: item.batteryLevel
        }))

      console.log('处理后的轨迹数据:', filteredData)
      console.log('处理后数据长度:', filteredData.length)

      return filteredData
    }
  },
  watch: {
    visible(newVal) {
      console.log('=== 详情抽屉显示状态变化 ===')
      console.log('抽屉是否显示:', newVal)
      console.log('当前活动标签页:', this.activeTabValue)

      if (newVal) {
        this.$nextTick(() => {
          console.log('抽屉打开，准备初始化地图')
          this.initMap()
        })
      }
    },
    activeTabValue(newVal) {
      if (newVal === 'track') {
        this.$nextTick(() => {
          this.initMap()
        })
      }
    },
    processedTrackData: {
      handler(newData) {
        console.log('=== processedTrackData 监听器触发 ===')
        console.log('新的轨迹数据:', newData)
        console.log('数据长度:', newData.length)
        console.log('当前地图实例:', this.map)

        this.trackPoints = newData
        if (this.map && newData.length > 0) {
          console.log('地图已初始化且有数据，开始绘制轨迹')
          this.drawTrack()
        } else {
          console.log('地图未初始化或无数据，跳过绘制')
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 监听ESC键退出全屏
    document.addEventListener('keydown', this.handleKeydown)

    // 监听全屏状态变化
    document.addEventListener('fullscreenchange', this.handleFullscreenChange)
    document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange)
    document.addEventListener('mozfullscreenchange', this.handleFullscreenChange)
    document.addEventListener('MSFullscreenChange', this.handleFullscreenChange)
  },
  beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener('keydown', this.handleKeydown)
    document.removeEventListener('fullscreenchange', this.handleFullscreenChange)
    document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange)
    document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange)
    document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange)

    this.clearPlayTimer()

    // 如果当前处于全屏状态，退出全屏
    if (this.isFullscreen) {
      this.exitFullscreen()
    }

    // 清理信息窗体
    if (this.infoWindow) {
      this.infoWindow.close()
      this.infoWindow = null
    }

    // 清理路径规划服务
    if (this.driving) {
      this.driving.clear()
      this.driving = null
    }

    // 清理地图
    if (this.map) {
      this.map.destroy()
    }
  },
  methods: {
    // 地图相关方法
    initMap() {
      console.log('=== 地图初始化调试 ===')
      console.log('当前map实例:', this.map)
      console.log('window.AMap是否存在:', !!window.AMap)

      if (this.map || !window.AMap) {
        console.log('地图已存在或AMap未加载，跳过初始化')
        return
      }

      const mapContainer = this.$refs.trackMap
      console.log('地图容器元素:', mapContainer)
      if (!mapContainer) {
        console.log('地图容器不存在，跳过初始化')
        return
      }

      console.log('开始初始化地图...')
      // 初始化地图
      this.map = new window.AMap.Map('track-map', {
        zoom: 13,
        center: [116.397428, 39.90923], // 默认北京
        mapStyle: 'amap://styles/normal'
      })

      console.log('地图初始化完成:', this.map)

      // 添加地图控件（兼容不同版本的API）
      this.addMapControls()

      // 如果有轨迹数据，绘制轨迹
      console.log('当前轨迹点数量:', this.trackPoints.length)
      if (this.trackPoints.length > 0) {
        console.log('开始绘制轨迹...')
        this.drawTrack()
      } else {
        console.log('没有轨迹数据，跳过绘制')
      }
    },

    drawTrack() {
      console.log('=== 轨迹绘制调试 ===')
      console.log('地图实例:', this.map)
      console.log('轨迹点数据:', this.trackPoints)
      console.log('轨迹点数量:', this.trackPoints.length)

      if (!this.map || this.trackPoints.length === 0) {
        console.log('地图未初始化或没有轨迹数据，跳过绘制')
        return
      }

      console.log('开始绘制轨迹...')

      // 清除之前的轨迹和标记
      this.clearTrack()

      // 初始化路径规划服务
      if (!this.driving) {
        console.log('初始化路径规划服务...')
        this.initDrivingService()
      }

      // 1. 添加所有轨迹点标记
      console.log('添加轨迹点标记...')
      this.addTrackPointMarkers()

      // 2. 添加起点和终点特殊标记
      console.log('添加起终点标记...')
      this.addStartEndMarkers()

      // 3. 创建当前位置标记（用于播放动画）
      console.log('创建当前位置标记...')
      this.createCurrentMarker()

      // 4. 绘制路径（使用路径规划或直线连接）
      console.log('绘制路径...')
      this.drawRoutePaths()

      // 5. 自适应显示所有点
      console.log('设置地图视野...')
      this.map.setFitView()

      console.log('轨迹绘制完成')
    },

    // 添加地图控件（兼容不同版本的API）
    addMapControls() {
      try {
        // 尝试添加比例尺控件
        if (window.AMap.Scale) {
          // 新版本API
          if (typeof window.AMap.Scale === 'function') {
            this.map.addControl(new window.AMap.Scale())
          } else {
            // 某些版本可能需要不同的初始化方式
            this.map.addControl(window.AMap.Scale())
          }
        }
      } catch (error) {
        console.warn('添加比例尺控件失败:', error)
      }

      try {
        // 尝试添加工具栏控件
        if (window.AMap.ToolBar) {
          // 新版本API
          if (typeof window.AMap.ToolBar === 'function') {
            this.map.addControl(new window.AMap.ToolBar())
          } else {
            // 某些版本可能需要不同的初始化方式
            this.map.addControl(window.AMap.ToolBar())
          }
        }
      } catch (error) {
        console.warn('添加工具栏控件失败:', error)
      }

      // 如果上述方法都失败，尝试使用插件方式加载
      if (!this.map.getControls || this.map.getControls().length === 0) {
        this.loadMapPlugins()
      }
    },

    // 加载地图插件
    loadMapPlugins() {
      if (!window.AMap || !window.AMap.plugin) {
        console.warn('高德地图API未完全加载')
        return
      }

      window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
        try {
          // 使用插件方式添加控件
          if (window.AMap.Scale) {
            const scale = new window.AMap.Scale()
            this.map.addControl(scale)
          }

          if (window.AMap.ToolBar) {
            const toolBar = new window.AMap.ToolBar()
            this.map.addControl(toolBar)
          }
        } catch (error) {
          console.warn('插件方式添加控件失败:', error)
        }
      })
    },

    // 初始化路径规划服务
    initDrivingService() {
      console.log('=== 初始化路径规划服务 ===')
      console.log('AMap.Driving 是否存在:', !!window.AMap.Driving)
      console.log('AMap.DrivingPolicy 是否存在:', !!window.AMap.DrivingPolicy)

      try {
        if (window.AMap.Driving) {
          const drivingOptions = {
            hideMarkers: true, // 隐藏默认标记
            showTraffic: false, // 不显示交通状况
            autoFitView: false // 不自动调整视野
          }

          // 设置路径规划策略
          if (window.AMap.DrivingPolicy) {
            drivingOptions.policy = window.AMap.DrivingPolicy.LEAST_TIME
            console.log('使用最短时间策略')
          } else {
            console.log('DrivingPolicy 不可用，使用默认策略')
          }

          this.driving = new window.AMap.Driving(drivingOptions)
          console.log('路径规划服务初始化成功:', this.driving)
        } else {
          console.log('AMap.Driving 不可用，尝试插件加载')
          this.loadDrivingPlugin()
        }
      } catch (error) {
        console.warn('初始化路径规划服务失败:', error)
        this.loadDrivingPlugin()
      }
    },

    // 加载路径规划插件
    loadDrivingPlugin() {
      console.log('尝试通过插件方式加载路径规划服务')

      if (!window.AMap || !window.AMap.plugin) {
        console.warn('高德地图API未完全加载，无法使用路径规划功能')
        return
      }

      window.AMap.plugin('AMap.Driving', () => {
        try {
          console.log('路径规划插件加载成功，创建服务实例')

          const drivingOptions = {
            hideMarkers: true,
            showTraffic: false,
            autoFitView: false
          }

          if (window.AMap.DrivingPolicy) {
            drivingOptions.policy = window.AMap.DrivingPolicy.LEAST_TIME
          }

          this.driving = new window.AMap.Driving(drivingOptions)
          console.log('插件方式路径规划服务初始化成功:', this.driving)

          // 如果有轨迹数据，重新绘制路径
          if (this.trackPoints.length > 1) {
            console.log('重新绘制路径')
            this.drawRoutePaths()
          }
        } catch (error) {
          console.warn('插件方式初始化路径规划服务失败:', error)
        }
      })
    },

    // 添加轨迹点标记
    addTrackPointMarkers() {
      this.trackPoints.forEach((point, index) => {
        // 跳过起点和终点，它们有特殊标记
        if (index === 0 || index === this.trackPoints.length - 1) {
          return
        }

        const marker = new window.AMap.Marker({
          position: [point.lng, point.lat],
          icon: new window.AMap.Icon({
            size: new window.AMap.Size(18, 24),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            imageOffset: new window.AMap.Pixel(-6, -24)
          }),
          title: `途径点 ${index + 1}`,
          extData: { pointIndex: index, pointData: point },
          zIndex: 50
        })

        // 添加鼠标悬停事件
        marker.on('mouseover', (e) => {
          this.showPointInfo(e.target, point)
        })

        marker.on('mouseout', () => {
          this.hidePointInfo()
        })

        this.trackPointMarkers.push(marker)
        this.map.add(marker)
      })
    },

    // 添加起点和终点标记
    addStartEndMarkers() {
      if (this.trackPoints.length === 0) return

      // 起点标记 - 使用绿色标记表示起点（增大尺寸，提高层级）
      const startSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
        <circle cx="20" cy="20" r="18" fill="#52c41a" stroke="#fff" stroke-width="3"/>
        <text x="20" y="26" text-anchor="middle" fill="#fff" font-size="14" font-weight="bold">起</text>
      </svg>`

      const startMarker = new window.AMap.Marker({
        position: [this.trackPoints[0].lng, this.trackPoints[0].lat],
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(40, 40),
          image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(startSvg),
          imageOffset: new window.AMap.Pixel(-20, -20)
        }),
        title: '起点',
        extData: { pointIndex: 0, pointData: this.trackPoints[0] },
        zIndex: 200
      })

      // 终点标记 - 使用红色标记表示终点（增大尺寸，提高层级）
      const endSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
        <circle cx="20" cy="20" r="18" fill="#ff4d4f" stroke="#fff" stroke-width="3"/>
        <text x="20" y="26" text-anchor="middle" fill="#fff" font-size="14" font-weight="bold">终</text>
      </svg>`

      const endMarker = new window.AMap.Marker({
        position: [this.trackPoints[this.trackPoints.length - 1].lng, this.trackPoints[this.trackPoints.length - 1].lat],
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(40, 40),
          image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(endSvg),
          imageOffset: new window.AMap.Pixel(-20, -20)
        }),
        title: '终点',
        extData: {
          pointIndex: this.trackPoints.length - 1,
          pointData: this.trackPoints[this.trackPoints.length - 1]
        },
        zIndex: 200
      })

      // 为起点和终点也添加悬停事件
      startMarker.on('mouseover', (e) => {
        this.showPointInfo(e.target, this.trackPoints[0])
      })
      startMarker.on('mouseout', () => {
        this.hidePointInfo()
      })

      endMarker.on('mouseover', (e) => {
        this.showPointInfo(e.target, this.trackPoints[this.trackPoints.length - 1])
      })
      endMarker.on('mouseout', () => {
        this.hidePointInfo()
      })

      this.markers.push(startMarker, endMarker)
      this.map.add([startMarker, endMarker])
    },

    // 创建当前位置标记
    createCurrentMarker() {
      const currentSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20">
        <circle cx="10" cy="10" r="8" fill="#ff4d4f" stroke="#fff" stroke-width="2"/>
      </svg>`

      this.currentMarker = new window.AMap.Marker({
        position: [this.trackPoints[0].lng, this.trackPoints[0].lat],
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(20, 20),
          image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(currentSvg),
          imageOffset: new window.AMap.Pixel(-10, -10)
        }),
        title: '当前位置',
        zIndex: 300 // 确保当前位置标记在最上层，但低于起终点
      })

      this.map.add(this.currentMarker)
    },

    // 绘制路径（使用路径规划或直线连接）
    async drawRoutePaths() {
      console.log('=== 开始绘制路径 ===')
      console.log('轨迹点数量:', this.trackPoints.length)

      if (this.trackPoints.length < 2) {
        console.log('轨迹点少于2个，跳过路径绘制')
        return
      }

      // 检查路径规划服务是否可用
      if (!this.driving) {
        console.warn('路径规划服务不可用，使用直线连接')
        this.drawAllStraightLines()
        return
      }

      console.log('使用路径规划服务绘制实际道路路径')

      // 逐点连接，绘制相邻两点之间的实际道路路径
      let successCount = 0
      let failCount = 0

      for (let i = 0; i < this.trackPoints.length - 1; i++) {
        const startPoint = this.trackPoints[i]
        const endPoint = this.trackPoints[i + 1]

        console.log(`绘制路径段 ${i + 1}/${this.trackPoints.length - 1}: 从 ${startPoint.address} 到 ${endPoint.address}`)

        try {
          await this.drawSingleRoute(startPoint, endPoint, i)
          successCount++
          console.log(`路径段 ${i + 1} 规划成功`)
        } catch (error) {
          console.warn(`路径段 ${i + 1} 规划失败，使用直线连接:`, error)
          this.drawStraightLine(startPoint, endPoint)
          failCount++
        }

        // 添加延迟避免API调用过于频繁
        if (i < this.trackPoints.length - 2) {
          await this.delay(300) // 增加延迟时间
        }
      }

      console.log(`路径绘制完成: 成功 ${successCount} 段, 失败 ${failCount} 段`)
    },

    // 绘制所有直线连接（降级方案）
    drawAllStraightLines() {
      for (let i = 0; i < this.trackPoints.length - 1; i++) {
        this.drawStraightLine(this.trackPoints[i], this.trackPoints[i + 1])
      }
    },

    // 绘制单段路径
    drawSingleRoute(startPoint, endPoint, segmentIndex = 0) {
      return new Promise((resolve, reject) => {
        const startCoord = [startPoint.lng, startPoint.lat]
        const endCoord = [endPoint.lng, endPoint.lat]

        console.log(`路径规划请求 ${segmentIndex + 1}:`, {
          起点: startCoord,
          终点: endCoord,
          起点地址: startPoint.address,
          终点地址: endPoint.address
        })

        // 检查坐标有效性
        if (!this.isValidCoordinate(startCoord) || !this.isValidCoordinate(endCoord)) {
          reject(new Error('坐标无效'))
          return
        }

        // 检查距离，如果两点距离太近，直接用直线连接
        const distance = this.calculateDistance(startPoint, endPoint)
        if (distance < 100) { // 小于100米直接用直线
          console.log(`距离太近 (${distance.toFixed(0)}m)，使用直线连接`)
          this.drawStraightLine(startPoint, endPoint)
          resolve()
          return
        }

        console.log(`两点距离: ${distance.toFixed(0)}m，使用路径规划`)

        this.driving.search(
          startCoord,
          endCoord,
          (status, result) => {
            console.log(`路径规划结果 ${segmentIndex + 1}:`, { status, result })

            if (status === 'complete' && result.routes && result.routes.length > 0) {
              const route = result.routes[0]
              const path = []

              // 提取路径坐标点
              route.steps.forEach(step => {
                if (step.path && step.path.length > 0) {
                  step.path.forEach(point => {
                    path.push([point.lng, point.lat])
                  })
                }
              })

              console.log(`路径段 ${segmentIndex + 1} 坐标点数量:`, path.length)

              if (path.length > 0) {
                const polyline = new window.AMap.Polyline({
                  path: path,
                  strokeColor: '#1890ff',
                  strokeWeight: 4,
                  strokeOpacity: 0.8,
                  lineJoin: 'round',
                  lineCap: 'round',
                  zIndex: 10
                })

                this.routePolylines.push(polyline)
                this.map.add(polyline)

                console.log(`路径段 ${segmentIndex + 1} 绘制成功`)
                resolve()
              } else {
                console.warn(`路径段 ${segmentIndex + 1} 没有有效路径点`)
                reject(new Error('没有有效路径点'))
              }
            } else {
              console.warn(`路径段 ${segmentIndex + 1} 规划失败:`, status, result)
              reject(new Error(`路径规划失败: ${status}`))
            }
          }
        )
      })
    },

    // 绘制直线连接（降级方案）
    drawStraightLine(startPoint, endPoint) {
      console.log('绘制直线连接:', {
        起点: [startPoint.lng, startPoint.lat],
        终点: [endPoint.lng, endPoint.lat],
        起点地址: startPoint.address,
        终点地址: endPoint.address
      })

      const polyline = new window.AMap.Polyline({
        path: [
          [startPoint.lng, startPoint.lat],
          [endPoint.lng, endPoint.lat]
        ],
        strokeColor: '#1890ff',
        strokeWeight: 3, // 稍细一些
        strokeOpacity: 0.6, // 稍透明一些
        strokeStyle: 'dashed', // 使用虚线表示直线连接
        zIndex: 5 // 层级低于路径规划线
      })

      this.routePolylines.push(polyline)
      this.map.add(polyline)
      console.log('直线连接绘制完成')
    },

    // 显示点位信息
    showPointInfo(marker, pointData) {
      if (this.infoWindow) {
        this.infoWindow.close()
      }

      const content = `
        <div style="padding: 8px; min-width: 200px; font-size: 12px;">
          <div style="font-weight: bold; margin-bottom: 5px; color: #333;">位置信息</div>
          <div style="margin-bottom: 3px;">
            <span style="color: #666;">时间：</span>
            <span>${this.parseTime(pointData.time, '{y}-{m}-{d} {h}:{i}:{s}')}</span>
          </div>
          <div style="margin-bottom: 3px;">
            <span style="color: #666;">位置：</span>
            <span>${pointData.address || '未知位置'}</span>
          </div>
          ${pointData.temperature !== null && pointData.temperature !== undefined ?
            `<div style="margin-bottom: 3px;">
              <span style="color: #666;">温度：</span>
              <span>${pointData.temperature}°C</span>
            </div>` : ''
          }
          ${pointData.humidity !== null && pointData.humidity !== undefined ?
            `<div style="margin-bottom: 3px;">
              <span style="color: #666;">湿度：</span>
              <span>${pointData.humidity}%</span>
            </div>` : ''
          }
          ${pointData.batteryLevel ?
            `<div>
              <span style="color: #666;">电量：</span>
              <span>${pointData.batteryLevel}%</span>
            </div>` : ''
          }
        </div>
      `

      this.infoWindow = new window.AMap.InfoWindow({
        content: content,
        offset: new window.AMap.Pixel(0, -30),
        closeWhenClickMap: false,
        autoMove: true
      })

      this.infoWindow.open(this.map, marker.getPosition())
    },

    // 隐藏点位信息
    hidePointInfo() {
      if (this.infoWindow) {
        this.infoWindow.close()
        this.infoWindow = null
      }
    },

    // 验证坐标有效性
    isValidCoordinate(coord) {
      if (!coord || coord.length !== 2) return false
      const [lng, lat] = coord
      return lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90 && lng !== 0 && lat !== 0
    },

    // 计算两点之间的距离（米）
    calculateDistance(point1, point2) {
      const R = 6371000 // 地球半径（米）
      const lat1 = point1.lat * Math.PI / 180
      const lat2 = point2.lat * Math.PI / 180
      const deltaLat = (point2.lat - point1.lat) * Math.PI / 180
      const deltaLng = (point2.lng - point1.lng) * Math.PI / 180

      const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
                Math.cos(lat1) * Math.cos(lat2) *
                Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))

      return R * c
    },

    // 延迟函数
    delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms))
    },

    clearTrack() {
      // 清除原有轨迹线
      if (this.trackPolyline) {
        this.map.remove(this.trackPolyline)
        this.trackPolyline = null
      }

      // 清除路径规划线段
      if (this.routePolylines.length > 0) {
        this.map.remove(this.routePolylines)
        this.routePolylines = []
      }

      // 清除当前位置标记
      if (this.currentMarker) {
        this.map.remove(this.currentMarker)
        this.currentMarker = null
      }

      // 清除起点终点标记
      if (this.markers.length > 0) {
        this.map.remove(this.markers)
        this.markers = []
      }

      // 清除轨迹点标记
      if (this.trackPointMarkers.length > 0) {
        this.map.remove(this.trackPointMarkers)
        this.trackPointMarkers = []
      }

      // 关闭信息窗体
      if (this.infoWindow) {
        this.infoWindow.close()
        this.infoWindow = null
      }
    },

    handleOpen() {
      this.$emit('open')
    },
    handleTabClick(tab) {
      console.log('=== 详情抽屉标签页切换 ===')
      console.log('切换到标签页:', tab.name)

      this.$emit('tab-click', tab)

      // 如果切换到轨迹地图标签页，初始化地图
      if (tab.name === 'track') {
        console.log('切换到轨迹地图标签页，准备初始化地图')
        this.$nextTick(() => {
          console.log('nextTick 执行，开始初始化地图')
          this.initMap()
        })
      }
    },

    // 播放控制方法
    togglePlay() {
      if (this.isPlaying) {
        this.pausePlay()
      } else {
        this.startPlay()
      }
    },

    startPlay() {
      if (this.trackPoints.length === 0) {
        return
      }

      this.isPlaying = true
      this.playTimer = setInterval(() => {
        if (this.currentPointIndex < this.trackPoints.length - 1) {
          this.currentPointIndex++
          this.playProgress = this.currentPointIndex
          this.updateCurrentPosition()
        } else {
          this.pausePlay()
        }
      }, 1000 / this.playSpeed)
    },

    pausePlay() {
      this.isPlaying = false
      this.clearPlayTimer()
    },

    resetTrack() {
      this.pausePlay()
      this.currentPointIndex = 0
      this.playProgress = 0
      this.updateCurrentPosition()
    },

    clearPlayTimer() {
      if (this.playTimer) {
        clearInterval(this.playTimer)
        this.playTimer = null
      }
    },

    onProgressChange(value) {
      this.currentPointIndex = value
      this.updateCurrentPosition()
    },

    updateCurrentPosition() {
      if (this.currentMarker && this.trackPoints[this.currentPointIndex]) {
        const point = this.trackPoints[this.currentPointIndex]
        this.currentMarker.setPosition([point.lng, point.lat])

        // 关闭之前的悬停信息窗体，避免冲突
        if (this.infoWindow) {
          this.infoWindow.close()
          this.infoWindow = null
        }

        // 创建播放时的信息窗体（样式与悬停信息一致）
        const playInfoWindow = new window.AMap.InfoWindow({
          content: `
            <div style="padding: 8px; min-width: 200px; font-size: 12px;">
              <div style="font-weight: bold; margin-bottom: 5px; color: #333;">当前位置</div>
              <div style="margin-bottom: 3px;">
                <span style="color: #666;">时间：</span>
                <span>${this.parseTime(point.time, '{y}-{m}-{d} {h}:{i}:{s}')}</span>
              </div>
              <div style="margin-bottom: 3px;">
                <span style="color: #666;">位置：</span>
                <span>${point.address || '未知位置'}</span>
              </div>
              ${point.temperature !== null && point.temperature !== undefined ?
                `<div style="margin-bottom: 3px;">
                  <span style="color: #666;">温度：</span>
                  <span>${point.temperature}°C</span>
                </div>` : ''
              }
              ${point.humidity !== null && point.humidity !== undefined ?
                `<div style="margin-bottom: 3px;">
                  <span style="color: #666;">湿度：</span>
                  <span>${point.humidity}%</span>
                </div>` : ''
              }
              ${point.batteryLevel ?
                `<div>
                  <span style="color: #666;">电量：</span>
                  <span>${point.batteryLevel}%</span>
                </div>` : ''
              }
            </div>
          `,
          offset: new window.AMap.Pixel(0, -30),
          closeWhenClickMap: false
        })

        playInfoWindow.open(this.map, [point.lng, point.lat])

        // 2秒后自动关闭信息窗体（播放时间短一些）
        setTimeout(() => {
          playInfoWindow.close()
        }, 2000)
      }
    },

    // 全屏控制方法
    async toggleFullscreen() {
      console.log('=== 切换全屏状态 ===')
      console.log('当前全屏状态:', this.isFullscreen)

      if (!this.isFullscreen) {
        // 进入全屏
        await this.enterFullscreen()
      } else {
        // 退出全屏
        await this.exitFullscreen()
      }
    },

    // 进入全屏
    async enterFullscreen() {
      try {
        const mapContainer = this.$refs.trackMap
        if (!mapContainer) {
          console.warn('地图容器不存在，无法进入全屏')
          return
        }

        console.log('请求进入全屏模式')

        // 使用浏览器原生全屏API
        if (mapContainer.requestFullscreen) {
          await mapContainer.requestFullscreen()
        } else if (mapContainer.webkitRequestFullscreen) {
          await mapContainer.webkitRequestFullscreen()
        } else if (mapContainer.mozRequestFullScreen) {
          await mapContainer.mozRequestFullScreen()
        } else if (mapContainer.msRequestFullscreen) {
          await mapContainer.msRequestFullscreen()
        } else {
          console.warn('浏览器不支持全屏API，使用CSS全屏')
          this.isFullscreen = true
          this.resizeMap()
          return
        }

        console.log('全屏请求已发送')
      } catch (error) {
        console.warn('进入全屏失败:', error)
        // 降级为CSS全屏
        this.isFullscreen = true
        this.resizeMap()
      }
    },

    // 退出全屏
    async exitFullscreen() {
      try {
        console.log('请求退出全屏模式')

        if (document.exitFullscreen) {
          await document.exitFullscreen()
        } else if (document.webkitExitFullscreen) {
          await document.webkitExitFullscreen()
        } else if (document.mozCancelFullScreen) {
          await document.mozCancelFullScreen()
        } else if (document.msExitFullscreen) {
          await document.msExitFullscreen()
        } else {
          console.warn('浏览器不支持退出全屏API，使用CSS退出')
          this.isFullscreen = false
          this.resizeMap()
          return
        }

        console.log('退出全屏请求已发送')
      } catch (error) {
        console.warn('退出全屏失败:', error)
        // 降级为CSS退出全屏
        this.isFullscreen = false
        this.resizeMap()
      }
    },

    // 调整地图尺寸
    resizeMap() {
      this.$nextTick(() => {
        if (this.map) {
          console.log('调整地图尺寸')
          this.map.getSize()
          this.map.setFitView()
        }
      })
    },

    // 监听全屏状态变化
    handleFullscreenChange() {
      const isCurrentlyFullscreen = !!(
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement
      )

      console.log('全屏状态变化:', isCurrentlyFullscreen)
      this.isFullscreen = isCurrentlyFullscreen
      this.resizeMap()
    },

    handleKeydown(event) {
      if (event.key === 'Escape' && this.isFullscreen) {
        console.log('ESC键退出全屏')
        this.exitFullscreen()
      }
    },

    handleOperationPagination() {
      this.$emit('operation-pagination')
    },
    handleTransferPagination() {
      this.$emit('transfer-pagination')
    },
    handleLocationPagination() {
      this.$emit('location-pagination')
    },
    /** 获取操作类型名称 */
    getOperationTypeName(type) {
      const typeMap = {
        '1': '新增',
        '2': '定位器绑定',
        '3': '定位器解绑',
        '4': '清洗',
        '5': '折叠整理',
        '6': '装箱',
        '7': '拆箱',
        '8': '封存',
        '9': '解封',
        '10': '维修',
        '11': '检查'
      }
      return typeMap[type] || '未知'
    },
    /** 获取操作类型标签样式 */
    getOperationTypeTag(type) {
      const tagMap = {
        '1': 'success',   // 新增
        '2': 'primary',   // 定位器绑定
        '3': 'warning',   // 定位器解绑
        '4': 'info',      // 清洗
        '5': '',          // 折叠整理
        '6': 'primary',   // 装箱
        '7': 'danger',    // 拆箱
        '8': 'info',      // 封存
        '9': 'success',   // 解封
        '10': 'warning',  // 维修
        '11': ''          // 检查
      }
      return tagMap[type] || ''
    },
    /** 获取移库状态名称 */
    getTransferStatusName(status) {
      const statusMap = {
        '1': '进行中',
        '2': '已完成',
        '3': '已取消'
      }
      return statusMap[status] || '未知'
    },
    /** 获取移库状态标签样式 */
    getTransferStatusTag(status) {
      const tagMap = {
        '1': 'warning',  // 进行中
        '2': 'success',  // 已完成
        '3': 'danger'    // 已取消
      }
      return tagMap[status] || ''
    }
  }
}
</script>

<style scoped>
.drawer-container {
  position: relative;
  height: 100%;
}

.drawer-content {
  padding: 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.tab-content {
  padding: 20px 0;
}

.tab-content .el-table {
  margin-bottom: 20px;
}

/* 标签页样式优化 */
.el-tabs--card > .el-tabs__header .el-tabs__nav {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.el-tabs--card > .el-tabs__header .el-tabs__item {
  border-left: 1px solid #e4e7ed;
  border-top: none;
  border-bottom: none;
  border-right: none;
}

.el-tabs--card > .el-tabs__header .el-tabs__item:first-child {
  border-left: none;
}

.el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

/* 轨迹地图样式 */
.track-map-container {
  position: relative;
  width: 100%;
  height: 500px;
}

.track-map {
  width: 100%;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

/* 全屏模式样式 */
.track-map.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  border: none;
  border-radius: 0;
  background: #fff;
}

/* 浏览器原生全屏模式样式 */
.track-map:fullscreen {
  width: 100vw;
  height: 100vh;
  border: none;
  border-radius: 0;
  background: #fff;
}

.track-map:-webkit-full-screen {
  width: 100vw;
  height: 100vh;
  border: none;
  border-radius: 0;
  background: #fff;
}

.track-map:-moz-full-screen {
  width: 100vw;
  height: 100vh;
  border: none;
  border-radius: 0;
  background: #fff;
}

.track-map:-ms-fullscreen {
  width: 100vw;
  height: 100vh;
  border: none;
  border-radius: 0;
  background: #fff;
}

.fullscreen-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1000;
}

/* 全屏模式下的按钮样式 */
.track-map:fullscreen .fullscreen-btn,
.track-map:-webkit-full-screen .fullscreen-btn,
.track-map:-moz-full-screen .fullscreen-btn,
.track-map:-ms-fullscreen .fullscreen-btn,
.track-map.fullscreen .fullscreen-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 10000;
  background: rgba(24, 144, 255, 0.9);
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.track-controls {
  margin-top: 15px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.control-buttons {
  display: flex;
  gap: 10px;
}

.speed-control {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.progress-control {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  flex: 1;
  min-width: 300px;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
  font-size: 14px;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-data p {
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .track-controls {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .progress-control {
    min-width: auto;
  }

  .control-buttons {
    justify-content: center;
  }

  .speed-control {
    justify-content: center;
  }
}
</style>
